package logic

import (
	"context"
	"gozero_test/common/cryptx"
	"gozero_test/common/errorx"
	"gozero_test/model"

	"gozero_test/internal/svc"
	"gozero_test/internal/types"

	"github.com/tal-tech/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) RegisterLogic {
	return RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req types.RegisterRequest) (*types.RegisterResponse, error) {
	// 判断手机号是否已经注册
	_, err := l.svcCtx.UserModel.FindOneByMobile(req.Mobile)
	if err == nil {
		return nil, errorx.NewCodeError(1000, "该用户已存在")
	}
	if err == model.ErrNotFound {
		newUser := model.User{
			Name:     req.Name,
			Gender:   req.Gender,
			Mobile:   req.Mobile,
			Password: cryptx.PasswordEncrypt(l.svcCtx.Config.Salt, req.Password),
		}

		res, err := l.svcCtx.UserModel.Insert(&newUser)
		if err != nil {
			return nil, errorx.NewCodeError(5000, err.Error())
		}

		newUser.Id, err = res.LastInsertId()
		if err != nil {
			return nil, errorx.NewCodeError(5000, err.Error())
		}

		return &types.RegisterResponse{
			Id:     newUser.Id,
			Name:   newUser.Name,
			Gender: newUser.Gender,
			Mobile: newUser.Mobile,
		}, nil
	}
	return nil, errorx.NewCodeError(5000, err.Error())
}
